"""
邮件配置数据模型
"""

from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Boolean, Index
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base


class EmailConfig(Base):
    """邮件配置模型"""
    __tablename__ = "email_configs"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, comment="配置名称")
    smtp_host = Column(String(255), nullable=False, comment="SMTP服务器地址")
    smtp_port = Column(Integer, nullable=False, comment="SMTP端口")
    username = Column(String(255), nullable=False, comment="SMTP用户名")
    password = Column(Text, nullable=False, comment="SMTP密码")
    from_email = Column(String(255), nullable=False, comment="发件人邮箱")
    from_name = Column(String(100), nullable=True, comment="发件人姓名")
    encryption = Column(String(20), nullable=False, default="none", comment="加密类型")
    use_ssl = Column(Boolean, nullable=False, default=False, comment="是否使用SSL")
    use_tls = Column(Boolean, nullable=False, default=False, comment="是否使用TLS")
    timeout = Column(Integer, nullable=False, default=30, comment="连接超时时间")
    description = Column(Text, nullable=True, comment="配置描述")
    is_active = Column(Boolean, nullable=False, default=True, comment="是否启用")

    # 关联字段
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关系
    user = relationship("User", back_populates="email_configs")

    # 索引
    __table_args__ = (
        Index('idx_email_configs_user_name', 'user_id', 'name'),
        Index('idx_email_configs_user_active', 'user_id', 'is_active'),
        Index('idx_email_configs_created_at', 'created_at'),
    )

    def __repr__(self):
        return f"<EmailConfig(id={self.id}, name='{self.name}', smtp_host='{self.smtp_host}')>"
